<?php
// +----------------------------------------------------------------------
// | Name: 咪乐多管理系统 [ 为了快速搭建软件应用而生的，希望能够帮助到大家提高开发效率。 ]
// +----------------------------------------------------------------------
// | Copyright: (c) 2020~2021 https://www.lvacms.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed: 这是一个自由软件，允许对程序代码进行修改，但希望您留下原有的注释。
// +----------------------------------------------------------------------
// | Author: 西安咪乐多软件 <997786358@qq.com>
// +----------------------------------------------------------------------
// | Version: V1
// +----------------------------------------------------------------------

/**
 * @Name 服务
 * @Description
 * @Auther 西安咪乐多软件
 * @Date 2021/11/20 19:06
 */
namespace Modules\ToolAdmin\Services\User;
use Modules\ToolAdmin\Models\ToolUser;
use Modules\ToolAdmin\Models\AdminProject;
use Modules\ToolAdmin\Services\BaseApiServices;
use EasyWeChat\Factory;
class MyServices extends BaseApiServices
{
    public function login(array $data)
    {
        $ext = AdminProject::query()->where(['id'=>$data['project_id']])->value( "ext");
        if(!$ext){
            $this->apiError('网络错误');
        }
        $ext = self::unSerialize($ext);
        if(!isset($ext['xcx_app_id']) || !isset($ext['xcx_app_secret'])){
            $this->apiError('网络错误');
        }
        $config = [
            'app_id' =>  $ext['xcx_app_id'],
            'secret' => $ext['xcx_app_secret'],
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $user = $app->auth->session($data['code']);
        if(!isset($user['openid'])){
            $this->apiError('网络错误');
        }
        $info = ToolUser::query()->where(['project_id'=>$data['project_id'],'xcx_open_id'=>$user['openid']])->first();
        if(!$info){
            $userInfo = [
                'project_id'=>$data['project_id'],
                'admin_id'=> 1,
                'xcx_open_id'=>$user['openid'],
                'type'=>1,
                'pid'=>isset($data['pid'])?$data['pid']:0,
                'status'=>0,
                'open'=>1,
                'integral'=>10,
                'created_at'=>date('Y-m-d H:i:s')
            ];
            $id = ToolUser::query()->insertGetId($userInfo);
            if(!$id){
                $this->apiError('网络错误');
            }
            ToolUser::query()->where(['id'=>$id])->update([
                'nick_name'=> rand(1000,9999) . $id
            ]);
            $info = ToolUser::query()->where(['id'=>$id])->first();
        }
        $info = $info->toArray();
        return $this->apiSuccess('登录成功',$info);
    }
}
